<template>
  <page-meta
    :page-style="'overflow:' + (popupShow ? 'hidden' : 'visible')"
  ></page-meta>
  <view class="container">
    <HeadNav title="卡牌" back />
    <view class="search-bar">
      <input
        v-if="showSearchInput"
        focus
        class="input-bar-input"
        v-model.trim="pagination.context"
        @confirm="onSearch"
        confirm-type="search"
        @blur="blurHandle"
      />
      <view class="input-bar-show" v-else @tap="inputbarClick">
        <uni-icons type="search" size="23" color="#FFF"></uni-icons>
        <text class="input-bar-showtext">搜索</text>
      </view>
    </view>
    <view class="filter-bar">
      <view class="select-box">
        <picker
          @change="cardTypeChange"
          :value="cardTypeIndex"
          :range="range"
          range-key="cardTypeName"
        >
          <view class="picker-box">
            <text class="picker-box-text">{{
              pagination.cardTypeId
                ? range[cardTypeIndex].cardTypeName
                : '所有卡种'
            }}</text>
            <uni-icons type="down" size="14" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
      <view class="select-box">
        <picker
          @change="campChange"
          :value="campIndex"
          :range="campsList"
          range-key="dictLabel"
        >
          <view class="picker-box">
            <text class="picker-box-text">{{
              pagination.camp ? campsList[campIndex].dictLabel : '所有角色'
            }}</text>
            <uni-icons type="down" size="14" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
      <view class="select-box">
        <!-- <uni-data-select placeholder="卡包" v-model="selectVal2" :localdata="range2" :clear="false"
						@change="selectChange"></uni-data-select> -->
        <picker
          @change="packIdChange"
          :value="packIdIndex"
          :range="range2"
          range-key="packName"
        >
          <view class="picker-box">
            <text class="picker-box-text">{{
              pagination.packId ? range2[packIdIndex].packName : '所有卡包'
            }}</text>
            <uni-icons type="down" size="14" color="#999"></uni-icons>
          </view>
        </picker>
      </view>

      <!-- <view class="filter-bar-right"> -->

      <view
        class="btn-search-box"
        @tap="showSearchPopup"
        style="height: 70rpx; box-sizing: border-box"
      >
        <uni-icons type="settings" size="22"></uni-icons>
      </view>
      <!-- </view> -->
    </view>
    <view class="filter-bar2">
      <!-- <view class="btn-reset" @tap="handleReset">
				重置
			</view> -->
      <button type="default" plain="true" class="btn-reset2" @tap="handleReset">
        重置
      </button>
    </view>
    <view class="card-bar">
      <view class="tag-item-title">
        <view class="result-border result-border-l"></view>
        <text> 搜索结果 </text>
        <view class="result-border"></view>
      </view>
      <scroll-view scroll-y class="card-list-height" @scrolltolower="getData">
        <view class="card-list">
          <view
            class="card-item"
            @tap="redirectFunc(item.id)"
            v-for="item of dataList"
            :key="item.id"
          >
            <image
              :src="item.fileUrl"
              class="card-image"
              webp
              lazy-load
            ></image>
          </view>
          <!-- <view class="card-item" @tap="redirectFunc">
					<image src="@/static/images/card3.png" class="card-image" webp></image>
				</view> -->
        </view>
        <uni-load-more
          v-if="showLoadMore"
          :status="scrollLimit.loadingStatus"
        />
      </scroll-view>
    </view>
  </view>
  <!-- 普通弹窗 -->
  <uni-popup
    ref="popupRef"
    background-color="#fff"
    type="right"
    @change="popupChange"
  >
    <view
      :style="{ paddingTop: store.menuButtonInfo.bottom + 'px' }"
      class="popup-content popup-height"
    >
      <scroll-view class="drawer-height" scroll-y="true">
        <!-- <view class="search-filters">
					<view class="search-filters-title">
						等级
					</view>
					<view class="search-filters-list">
						<view class="item" :class="{active: cardLevel.dictValue=== pagination.cardLevel}"
							v-for="(cardLevel) of cardLevelList" :key="cardLevel.dictCode"
							@tap="onItemClick('cardLevel',cardLevel.dictValue)">
							{{cardLevel.dictLabel}}
						</view>
					</view>
				</view> -->
        <!-- <view class="search-filters">
					<view class="search-filters-title">
						费用
					</view>
					<view class="search-filters-list">
						<view class="item" :class="{active: cost.dictValue=== pagination.cost}"
							v-for="(cost) of costsList" :key="cost.dictCode" @tap="onItemClick('cost',cost.dictValue)">
							{{cost.dictLabel}}
						</view>
					</view>
				</view> -->

        <!-- <view class="search-filters">
					<view class="search-filters-title">
						颜色
					</view>
					<view class="search-filters-list">
						<view class="item" :class="{active: color.dictValue=== pagination.color}"
							v-for="(color) of colorsList" :key="color.dictCode"
							@tap="onItemClick('color',color.dictValue)">
							{{color.dictLabel}}
						</view>
					</view>
				</view> -->
        <view class="search-filters">
          <view class="search-filters-title">
            <view class="search-icon"></view> <text>标签</text>
          </view>
          <view class="search-filters-list">
            <input
              class="search-input"
              v-model.trim="pagination.tags"
              @confirm="popupSearch"
              confirm-type="search"
              placeholder="输入标签"
              placeholder-style="font-size: 28rpx;"
            />
          </view>
        </view>
        <view class="search-filters">
          <view class="search-filters-title">
            <view class="search-icon"></view>
            <text>卡牌能力</text>
          </view>
          <view class="search-filters-list">
            <input
              class="search-input"
              v-model.trim="pagination.effect"
              @confirm="popupSearch"
              confirm-type="search"
              placeholder="输入卡牌能力"
              placeholder-style="font-size: 28rpx;"
            />
          </view>
        </view>
        <template v-if="extraDataList.length">
          <view
            class="search-filters"
            v-for="(extraData, extraDataIndex) of extraDataList"
            :key="extraData.key"
          >
            <view class="search-filters-title">
              <view class="search-icon"></view>
              <text>{{ extraData.value }}</text>
            </view>
            <view class="search-filters-list">
              <template v-if="extraData.displayType === 'option'">
                <view
                  class="item"
                  :class="{
                    active: extraData.activeIndex?.includes(
                      extraDataItem.dictLabel
                    )
                  }"
                  v-for="extraDataItem of extraData.sysDictDataList"
                  :key="extraDataItem.dictCode"
                  @tap="
                    onItemClick(
                      'extraData',
                      extraDataItem.dictLabel,
                      extraDataIndex
                    )
                  "
                >
                  {{ extraDataItem.dictLabel }}
                </view>
              </template>
              <template v-else>
                <input
                  class="search-input"
                  v-model.trim="extraData.activeIndex"
                  @confirm="popupSearch"
                  confirm-type="search"
                  :placeholder="'输入' + extraData.value"
                  placeholder-style="font-size: 28rpx;"
                />
              </template>
            </view>
          </view>
        </template>
      </scroll-view>
      <view class="search-button-bar">
        <view class="search-filters-reset" @tap="handleReset"> 重置 </view>
        <view class="search-filters-submit" @tap="popupSearch"> 搜索 </view>
      </view>

      <!-- </view> -->
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
import {
  getCardList,
  packSelectApi,
  cardTypeSelectApi,
  cardTypeSearchApi
} from '@/api/card'
import { dictionaryApi } from '@/api/common'
import HeadNav from '@/components/HeadNav'
import { useDeviceStore } from '@/stores/modules/deviceStore'
const store = useDeviceStore()
const showSearchInput = ref(false)
const pagination = reactive({
  pageNum: 0,
  pageSize: 10,
  context: '',
  camp: '',
  // cost: '',
  // color: '',
  cardTypeId: '',
  packId: '',
  // cardLevel: '',
  tags: '',
  effect: ''
})
const scrollLimit = reactive({
  loadingStatus: '',
  pageLimit: false
})

const showLoadMore = ref(true)
const dataList = ref([])
const cardTypeIndex = ref(0)
const packIdIndex = ref(0)
const campIndex = ref(0)
const range = ref([])
const range2 = ref([])
const popupRef = ref(null)
const popupShow = ref(false)
// const costsList = ref([])
const campsList = ref([])
// const colorsList = ref([])
// const cardLevelList = ref([])
const extraDataList = ref([])

onLoad(options => {
  console.log('options', options)
  for (const key in options) {
    if (key === 'keywords' && options[key]) {
      showSearchInput.value = true
      pagination.context = options.keywords
    } else if (options[key]) {
      pagination[key] = options[key]
    }
  }

  // if (options.camp) {
  // 	pagination.camp = options.camp
  // }
  getData()
  getDictionary()
})

const cardTypeChange = e => {
  // value: cardType.id,
  // text: cardType.cardTypeName
  console.log('cardType发送选择改变，携带值为：' + e.detail.value)
  cardTypeIndex.value = e.detail.value
  pagination.cardTypeId = range.value[e.detail.value].id
  clearData()
  cardTypeSearch()
}

const packIdChange = e => {
  // value: pack.id,
  // text: pack.packName
  console.log('packId发送选择改变，携带值为：' + e.detail.value)
  packIdIndex.value = e.detail.value
  pagination.packId = range2.value[e.detail.value].id
  clearData()
}

const campChange = e => {
  console.log('camp发送选择改变，携带值为：' + e.detail.value)
  campIndex.value = e.detail.value
  pagination.camp = campsList.value[e.detail.value].dictValue
  clearData()
}

const getData = async () => {
  if (scrollLimit.pageLimit) return
  pagination.pageNum++
  const params = {}

  for (const key in pagination) {
    if (pagination[key] !== '') {
      params[key] = pagination[key]
    }
  }
  const dynamicCardTypeConditionList = []
  // 判断额外数据
  for (const extraData of extraDataList.value) {
    if (extraData.activeIndex) {
      dynamicCardTypeConditionList.push({
        key: extraData.key,
        value: Array.isArray(extraData.activeIndex)
          ? extraData.activeIndex.join('|')
          : extraData.activeIndex
      })
    }
  }
  if (dynamicCardTypeConditionList.length)
    params.dynamicCardTypeConditionList = dynamicCardTypeConditionList

  showLoadMore.value = true
  scrollLimit.loadingStatus = 'loading'
  scrollLimit.pageLimit = true

  try {
    const res = await getCardList(params)
    dataList.value = dataList.value.concat(res.rows)

    if (dataList.value.length === 0) {
      // 查不到数据
      scrollLimit.pageLimit = true
      scrollLimit.loadingStatus = 'noMore'
    } else if (pagination.pageNum * pagination.pageSize >= res.total) {
      scrollLimit.pageLimit = true
      showLoadMore.value = false
    } else {
      scrollLimit.loadingStatus = 'more'
      scrollLimit.pageLimit = false
    }
  } catch (error) {
    console.log(error)
    scrollLimit.pageLimit = false
    // uni.showToast({
    // 	title: '查询产品数据失败，请稍后再试',
    // 	icon: 'error'
    // })
  }
}

const getDictionary = () => {
  // dictionaryApi('cost_dict').then(res => {
  // 	costsList.value = res.data
  // })

  // dictionaryApi('color_dict').then(res => {
  // 	colorsList.value = res.data
  // })

  dictionaryApi('camp_dict').then(res => {
    campsList.value = res.data
  })
  // dictionaryApi('card_level_dict').then(res => {
  // 	cardLevelList.value = res.data
  // })

  // 查询卡包下拉
  packSelectApi().then(packData => {
    range2.value = packData.data
  })
  // 卡牌类型下拉
  cardTypeSelectApi().then(cardTypeData => {
    range.value = cardTypeData.data
  })
}

const cardTypeSearch = async () => {
  const res = await cardTypeSearchApi(pagination.cardTypeId)
  extraDataList.value = res.data.map(item => {
    return {
      ...item,
      activeIndex: ''
    }
  })
}

const onItemClick = (name, value, index) => {
  console.log(name, value)
  switch (name) {
    // case 'camp':
    // 	if (pagination.camp === value) {
    // 		pagination.camp = ''
    // 	} else {
    // 		pagination.camp = value
    // 	}

    // 	break;
    // case 'color':
    // 	if (pagination.color === value) {
    // 		pagination.color = ''
    // 	} else {
    // 		pagination.color = value
    // 	}

    // 	break;
    // case 'cost':
    // 	if (pagination.cost === value) {
    // 		pagination.cost = ''
    // 	} else {
    // 		pagination.cost = value
    // 	}

    // 	break;
    // case 'cardLevel':
    // 	if (pagination.cardLevel === value) {
    // 		pagination.cardLevel = ''
    // 	} else {
    // 		pagination.cardLevel = value
    // 	}

    // 	break;
    case 'extraData':
      const activeIndex = extraDataList.value[index].activeIndex
      if (activeIndex) {
        // 存在
        // 判断是否存在当前值
        if (activeIndex.includes(value)) {
          extraDataList.value[index].activeIndex = activeIndex.filter(
            item => item !== value
          )
        } else {
          extraDataList.value[index].activeIndex = [...activeIndex, value]
        }
      } else {
        // 不存在当前值
        extraDataList.value[index].activeIndex = [value]
      }
      break
  }
}

const onSearch = () => {
  if (pagination.context.length > 0) {
    clearData()
  }
}

const popupSearch = () => {
  clearData()
  popupRef.value.close()
}

const clearData = () => {
  pagination.pageNum = 0
  scrollLimit.pageLimit = false
  dataList.value = []
  getData()
}

const handleReset = () => {
  pagination.camp = ''
  // pagination.cardLevel = ''
  // pagination.cost = ''
  // pagination.color = ''
  pagination.cardTypeId = ''
  pagination.packId = ''
  pagination.tags = ''
  pagination.effect = ''
  // pagination.context = ''
  // showSearchInput.value = false
  cardTypeIndex.value = 0
  packIdIndex.value = 0
  campIndex.value = 0
  extraDataList.value = []
  uni.showToast({
    title: '已重置搜索条件',
    icon: 'none'
  })
  clearData()
}

const blurHandle = event => {
  if (event.detail.value.length === 0) {
    showSearchInput.value = false
  }
}

const inputbarClick = () => {
  showSearchInput.value = true
}

const showSearchPopup = () => {
  popupRef.value.open()
}

const popupChange = e => {
  popupShow.value = e.show
}

const redirectFunc = id => {
  uni.navigateTo({
    url: '/pages/card/detail?id=' + id
  })
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #ebebeb;
  padding-bottom: env(safe-area-inset-bottom);
  height: 100vh;
  box-sizing: border-box;
}

.search-bar {
  padding: 16rpx 24rpx;
  //   background-color: #45463a;
  color: #fff;
  font-family: PingFangSC-Regular, sans-serif;
  font-size: 32rpx;
  background: url('https://ucp-tcg.com:18001/mc/app/static/d_bg.png');
  background-repeat: repeat-x;

  .input-bar-show {
    height: 72rpx;
    display: flex;
    width: 100%;
    justify-content: center;
    align-items: center;
    background-color: #ffffff4d;
    border-radius: 12rpx;
    flex: 1;

    .input-bar-showtext {
      line-height: 48rpx;
      margin-left: 8rpx;
      letter-spacing: 2rpx;
    }
  }

  .input-bar-input {
    height: 72rpx;
    background-color: #ffffff4d;
    border-radius: 12rpx;
    padding-left: 16rpx;
    font-size: 28rpx;
    // flex: 1;
  }

  // .btn-search {
  // 	border: 2rpx solid #CCCCCC;
  // 	padding: 16rpx 30rpx;
  // 	color: #FFFFFF;
  // 	font-size: 28rpx;
  // 	line-height: 40rpx;
  // 	border-radius: 12rpx;
  // 	background-color: #333333;
  // }
}

.filter-bar {
  padding: 32rpx 16rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // gap: 24rpx;
  width: 100%;
  box-sizing: border-box;

  // .filter-bar-left {
  // 	display: flex;

  // 	gap: 24rpx;
  // 	// width: 100%;
  // }

  // .filter-bar-right {
  // 	display: flex;
  // 	justify-content: flex-end;
  // 	gap: 24rpx;
  // 	align-items: center;

  // }

  .btn-search-box {
    background-color: #f1f1f1;
    border: 2rpx solid #ffffff;
    border-radius: 10rpx;
    padding: 14rpx 16rpx;
    box-shadow: 0 0 12rpx #00000029;
  }

  .select-box {
    width: 25%;
    box-shadow: 0 0 12rpx #00000029;

    .picker-box {
      font-size: 28rpx;
      border: 2rpx solid #e5e5e5;
      box-sizing: border-box;
      border-radius: 8rpx;
      padding: 0 10rpx;
      padding-left: 20rpx;
      position: relative;
      display: flex;
      -webkit-user-select: none;
      user-select: none;
      align-items: center;
      // border-bottom: solid 2rpx #e5e5e5;
      width: 100%;
      height: 70rpx;
      background-color: #f1f1f1;

      .picker-box-text {
        display: inline-block;
        color: #333;
        font-size: 24rpx;
        width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }

  // .btn-filter {
  // 	border-radius: 14rpx;
  // 	border: 2rpx solid #C9AC67;
  // 	box-shadow: 0 0 10rpx #00000059;
  // 	color: #BB9F5E;
  // 	font-size: 28rpx;
  // 	background-color: #3B3935;
  // 	width: 23.3%;
  // 	padding: 30rpx 0;
  // 	display: flex;
  // 	justify-content: center;
  // 	align-items: center;
  // 	letter-spacing: 4rpx;
  // }
}

.filter-bar2 {
  padding: 20rpx 16rpx 16rpx 16rpx;
  display: flex;
  justify-content: flex-end;
  width: 100%;
  box-sizing: border-box;

  // .btn-reset {
  // 	width: 15%;
  // 	background-color: #F1F1F1;
  // 	border: 2rpx solid #FFFFFF;
  // 	border-radius: 10rpx;
  // 	font-size: 28rpx;
  // 	padding: 14rpx 28rpx;
  // 	box-shadow: 0 0 12rpx #00000029;
  // 	text-align: center;
  // }

  .btn-reset2 {
    width: 18%;
    margin: 0;
    line-height: normal;
    font-size: 28rpx;
    // padding: 14rpx 28rpx;
    padding: 14rpx 16rpx;
  }
}

.card-bar {
  // padding: 0 32rpx;

  .tag-item-title {
    color: #bb9f5e;
    font-size: 32rpx;
    font-weight: 600;
    line-height: 44rpx;
    text-align: center;
    margin-bottom: 16rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16rpx;
    .result-border {
      height: 12rpx;
      width: 180rpx;
      background: url('https://ucp-tcg.com:18001/mc/app/static/searchresult-r.png')
        no-repeat center;
      background-size: cover;
    }
    .result-border-l {
      transform: rotate(180deg);
    }
  }

  .card-list-height {
    // max-height: calc(100vh - 380rpx - env(safe-area-inset-bottom));
    max-height: 63vh;
  }

  .card-list {
    padding: 0 24rpx;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .card-item {
      width: 48.5%;
      margin-bottom: 20rpx;

      .card-image {
        width: 100%;
        border-radius: 20rpx;
        height: 500rpx;
      }
    }
  }
}

@mixin height {
  /* #ifndef APP-NVUE */
  height: 100%;
  /* #endif */
  /* #ifdef APP-NVUE */
  flex: 1;
  /* #endif */
}

@mixin flex {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: column;
}

.popup-content {
  // @include flex;
  // align-items: center;
  // justify-content: center;
}

.popup-height {
  @include height;
  width: 80vw;
  position: relative;
  padding-top: 16rpx;
  box-sizing: border-box;
}

.search-filters {
  font-family: PingFangSC-Regular, sans-serif;
  // width: 100%;
  margin-bottom: 20rpx;
  padding: 0 15px;
  // box-sizing: border-box;
}

.search-filters-title {
  padding: 10rpx 0 18rpx;
  color: #333333;
  line-height: 44rpx;
  font-size: 32rpx;
  // border-bottom: 2rpx solid #d5d5d4;
  display: flex;
  gap: 24rpx;
  align-items: center;
  background-image: url('https://ucp-tcg.com:18001/mc/app/static/search-line.png');
  background-repeat: no-repeat;
  background-size: 100% 14rpx;
  background-position: bottom;
  .search-icon {
    width: 16rpx;
    height: 32rpx;
    background-image: url('https://ucp-tcg.com:18001/mc/app/static/icon_zs.png');
    background-repeat: no-repeat;
    background-size: cover;
  }
}

.search-filters-list {
  padding-top: 34rpx;
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;

  .search-input {
    width: 100%;
    height: 70rpx;
    background-color: #e5e7e9;
    border-color: #dddddd;
    border-radius: 12rpx;
    padding-left: 16rpx;
    font-size: 28rpx;
  }

  .item {
    width: 22%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2rpx solid #e5e5e5;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333333;
    padding: 16rpx 0;

    &.active {
      border-color: #bb9f5e;
    }
  }
}

.search-button-bar {
  display: flex;
  gap: 100rpx;
  justify-content: center;
  width: 100%;
  // border-top: 2rpx solid #DDDDDD;
  padding: 20rpx 32rpx;
  // padding-top: 40rpx;
  position: absolute;
  box-sizing: border-box;
  bottom: env(safe-area-inset-bottom);

  .search-filters-reset {
    border-radius: 12rpx;
    border: 2rpx solid #cccccc;
    background-color: #e1e1e1;
    // width: 264rpx;
    height: 72rpx;
    // line-height: 72rpx;
    width: 45%;
    // padding: 16rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;
    // text-align: center;
    color: #333333;
    background-image: url('https://ucp-tcg.com:18001/mc/app/static/btn-bg1.png');
    background-repeat: no-repeat;
    background-size: contain;
  }

  .search-filters-submit {
    border-radius: 12rpx;
    border: 2rpx solid #cccccc;
    background-color: #333333;
    // width: 264rpx;
    height: 72rpx;
    // line-height: 72rpx;
    // text-align: center;
    width: 45%;
    // padding: 16rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    background-image: url('https://ucp-tcg.com:18001/mc/app/static/btn-bg2.png');
    background-repeat: no-repeat;
    background-size: contain;
  }
}

.drawer-height {
  max-height: 85vh;
  box-sizing: border-box;
}
</style>
